package com.esd.device.controller;

import com.esd.common.pojo.R;
import com.esd.device.entity.vo.DeviceVo;
import com.esd.device.task.DeviceConstants;
import com.esd.device.utils.NumberUtils;
import com.esd.device.utils.Tcp_Utils_Nio;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class BaseOperationController {
    // 解析时间
    protected String getTimeResult(String result) {
        if (result != null) {
            return result.substring(15, 24);
        }
        return "";
    }

    // 分析数据，获取时间
    protected String setTime(String resultStr) {
        StringBuilder timeStr = new StringBuilder();
        String[] splitStr = resultStr.split(" ");
        int temp;
        for (int i = 0; i < splitStr.length; i++) {
            temp = NumberUtils.hexToInt(splitStr[i]);
            if (temp < 10) {
                timeStr.append("0").append(temp);
            } else {
                timeStr.append(temp);
            }
            if (i != splitStr.length - 1) {
                timeStr.append(":");
            }
        }
        return timeStr.toString();
    }

    protected String changeScaleToStr(String scaleStr) {
        String[] ss = scaleStr.split("-");
        if (ss.length!= 2) {
            return "";
        }
        return NumberUtils.intToHexString(Integer.parseInt(ss[1]), 2)
                + " " + NumberUtils.intToHexString(Integer.parseInt(ss[0]), 2);
    }

    protected R sendCommandForSearch(
            DeviceVo deviceVo ,
            String commandStr ,
            Tcp_Utils_Nio tcp_utils
    ){
        int timeout = 450 ;
        if(deviceVo.getDeviceTypeName().contains("新版接地电阻仪")){
            timeout = 500 ;
        }
        String hexString = NumberUtils.longToHexString(Long.parseLong(deviceVo.getStationId()),8);
        commandStr = hexString + " " + commandStr;
        String resultStr = "" ;
        ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
        reentrantLock.lock();
        try {
            resultStr = tcp_utils.sendCommand(deviceVo.getServerIp(), deviceVo.getServerPort(), commandStr, timeout);
        } catch (Exception e) {
            log.error("加锁失败！！ {}" , e.getMessage() );
        } finally {
            reentrantLock.unlock();
        }
        if (resultStr.equals("error")) {
            return  R.error( "可能网关停机了，请检查");
        } else if (resultStr.isEmpty()) {
            return  R.error( "无返回数据，终端" + deviceVo.getStationId() + "是否正常运行？");
        } else if (checkResult(commandStr, resultStr)) {
            return  R.ok(resultStr);
        }else {
            return  R.error("查询失败，返回的数据有误!!");
        }
    }

    protected R sendCommandForOperation(
            DeviceVo deviceVo ,
            String commandStr ,
            Tcp_Utils_Nio tcp_utils
    ){
        int timeout = 450 ;
        if(deviceVo.getDeviceTypeName().contains("新版接地电阻仪")){
            timeout = 500 ;
        }
        String resultStr = "" ;
        ReentrantLock reentrantLock = DeviceConstants.LockMap.get(deviceVo.getServerIp());
        reentrantLock.lock();
        try {
            resultStr = tcp_utils.sendCommand(deviceVo.getServerIp(), deviceVo.getServerPort(), commandStr, timeout);
        } catch (Exception e) {
            log.error("加锁失败！！ {}" , e.getMessage() );
        } finally {
            reentrantLock.unlock();
        }
        if (resultStr.equals("error")) {
            return  R.error( "可能网关停机了，请检查");
        } else if (resultStr.isEmpty()) {
            return  R.error( "无返回数据，终端" + deviceVo.getStationId() + "是否正常运行？");
        } else if (checkResult(commandStr, resultStr)) {
            return  R.ok(resultStr);
        }
        return  R.error("操作失败，返回的数据有误!!");
    }

    // 时间字符串 因为:在url中有特殊的作用，所以在前端传值时使用-代替
    protected String changeTimeStrToCommand(String timeString) {
        String[] ss = timeString.split("-");
        if (ss.length != 3) {
            return "";
        }
        int hour = Integer.parseInt(ss[0]);
        int minute = Integer.parseInt(ss[1]);
        int second = Integer.parseInt(ss[2]);
        return NumberUtils.intToHexString(hour, 2) + " "
                + NumberUtils.intToHexString(minute, 2) + " "
                + NumberUtils.intToHexString(second, 2);
    }

    // 校验返回结果是否正确
    private boolean checkResult(String command, String resultStr) {
        if (resultStr == null){
            return false;
        }
        command = command.toUpperCase().replace(" ", "").substring(0,8) ;
        resultStr = resultStr.toUpperCase().replace(" ", "").substring(0,8) ;
        return command.equals(resultStr) ;
    }
}
